package cn.stylefeng.guns.modular.robot.cmd.impl;

import cn.stylefeng.guns.modular.robot.cmd.abs.AbstractCmd;
import cn.stylefeng.guns.modular.robot.entity.Group;
import cn.stylefeng.guns.modular.robot.entity.Order;
import cn.stylefeng.guns.modular.robot.service.GroupService;
import cn.stylefeng.guns.modular.robot.service.OrderService;
import cn.stylefeng.guns.modular.robot.utils.RobotUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.telegram.telegrambots.bots.TelegramLongPollingBot;
import org.telegram.telegrambots.meta.api.objects.Update;

import javax.annotation.Resource;
import java.util.Locale;
import java.util.Objects;

@Slf4j
@Service
@Transactional
public class CmdQXF extends AbstractCmd {

    @Resource
    private OrderService orderService;
    @Resource
    private CmdZero cmdZero;
    @Resource
    private GroupService groupService;

    @Override
    public void exec(Update update, TelegramLongPollingBot bot) {
        String text = update.getMessage().getText();
        Long chatId = update.getMessage().getChatId();
        //查出账单
        Long orderId = Long.valueOf(text.toUpperCase(Locale.ROOT).replace("QXF", "").trim());
        Order order = orderService.getById(orderId);
        if (Objects.isNull(order) || !"下发".equals(order.getType())) {
            RobotUtils.sendText(chatId, "编号不存在！", bot);
            return;
        }
        //权限校验
        Long groupId = order.getGroupId();
        if (!chatId.equals(groupId)) {
            RobotUtils.sendText(chatId, "⚠非本群账单！你无权操作！", bot);
            return;
        }
        Group group = groupService.getGroupByTgGroupId(chatId);
        if (Boolean.TRUE.equals(group.getBatchStatus()) && !group.getBatchId().equals(order.getBatchId())) {
            RobotUtils.sendText(chatId, "已完成账单不能操作！", bot);
            return;
        }
        order.setIsDelete(true);
        orderService.updateById(order);
        RobotUtils.sendText(chatId, "账单： " + orderId + " 已清理", bot);
        cmdZero.sendOrderInfo(update, bot);
    }

    @Override
    public String getCmdName() {
        return "QXF";
    }

    @Override
    public String getDescribe() {
        return "QXF                           删除下发账单\n";
    }
}
